<template>
  <div class="container" >
    <!-- 标题栏 -->
    <div class="header">
      <h1>网络请求拦截器</h1>
      <div class="status">
        <span id="status-text">{{ isEnabled ? '已启用' : '已禁用' }}</span>
        <el-switch
          v-model="isEnabled"
          @change="toggleExtension"
          active-text="开启"
          inactive-text="关闭">
        </el-switch>
      </div>
    </div>

    <!-- 标签页 -->
    <el-tabs v-model="activeTab" type="border-card">

      <el-tab-pane label="Mock管理" name="mocks">
        <div class="section">
          <div class="section-header">
            <h3>Mock规则管理</h3>
            <el-button type="primary" @click="showMockModal()">新增Mock</el-button>
          </div>
          <div class="mock-list">
            <div class="list-header">
              <span>Mock规则数量</span>
              <el-tag type="info">{{ mockList.length }}</el-tag>
            </div>
            <div class="mock-table">
              <div
                  v-for="(mock, index) in mockList"
                  :key="index"
                  class="mock-item">
                <div class="mock-info">
                  <div class="mock-url">{{ mock.url }}</div>
<!--                  <div class="mock-meta">
                    <el-tag type="primary" size="mini">{{ mock.method || 'ALL' }}</el-tag>
                  </div>-->
                </div>
                <div class="mock-actions">
                  <el-switch
                      v-model="mock.enabled"
                      @change="saveMockList">
                  </el-switch>
                  <el-button
                      type="primary"
                      size="mini"
                      icon="el-icon-edit"
                      @click="editMock(index)">
                  </el-button>
                  <el-button
                      type="danger"
                      size="mini"
                      icon="el-icon-delete"
                      @click="deleteMock(index)">
                  </el-button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-tab-pane>

      <el-tab-pane label="域名白名单" name="whitelist">
        <div class="section">
          <h3>域名白名单设置</h3>
          <div class="input-group">
            <el-input
              v-model="newDomain"
              placeholder="输入域名前缀，如：api.baidu.com"
              @keyup.enter="addDomain">
            </el-input>
            <el-button type="primary" @click="addDomain">添加</el-button>
          </div>
          <div class="domain-list">
            <div class="list-header">
              <span>已添加的域名</span>
              <el-tag type="info">{{ domainList.length }}</el-tag>
            </div>
            <ul class="domain-items">
              <li v-for="(domain, domainindex) in domainList" :key="domainindex" class="domain-item" style="display: flex;">
                 <div style="flex:1;">
                   <template v-if="1==1">
                      <el-input
                           v-if="domain?._edit"
                           style="flex:1;"
                          v-model="domain.str"
                      ></el-input>
                     <span class="domain-name" v-else>{{ domain?.str }}</span>
                   </template>
                 </div>
                 <div>
                   <el-button
                       type="primary"
                       size="mini"
                       icon="el-icon-edit"
                       v-if="!domain?._edit"
                       @click="()=>{
                         domain._edit=true
                       }">
                     编辑
                   </el-button>
                   <el-button
                       type="primary"
                       size="mini"
                       icon="el-icon-save"
                       v-else
                       @click="()=>{
                           triggerUdpateDomain(domain,domainindex)
                       }">
                     保存
                   </el-button>
                   <el-button
                       type="danger"
                       size="mini"
                       icon="el-icon-delete"
                       @click="removeDomain(index)">
                   </el-button>
                 </div>

              </li>
            </ul>
          </div>
        </div>
      </el-tab-pane>

      <el-tab-pane label="关于项目">
        <!-- 关于 -->
          <div class="section-header">
            <h2>关于插件</h2>
            <p>插件信息和使用说明</p>
          </div>
          <div class="about-content">
            <div class="plugin-info">
              <h3>网络请求拦截器</h3>
              <p class="version">版本 1.0.0</p>
              <p class="description">
                这是一个强大的浏览器插件，用于拦截和模拟网络请求。
                支持域名白名单、Mock数据管理、请求监控等功能。
              </p>
            </div>

            <div class="features">
              <h4>主要功能</h4>
              <ul>
                <li>🌐 域名白名单管理 - 精确控制拦截范围</li>
                <li>🎭 Mock数据管理 - 灵活的API模拟</li>
                <li>📊 请求监控 - 详细的请求分析</li>
                <li>💾 数据导入导出 - 便捷的配置备份</li>
                <li>⚙️ 灵活配置 - 个性化设置选项</li>
              </ul>
            </div>

            <!-- 支付宝打赏 -->
            <div class="donation-section">
              <h4>【请作者喝咖啡】</h4>
              <div class="alipay-qr">
                <el-image :src="alipayicon" style="width: 100px;height: 100px;"
                          :preview-src-list="[alipayicon]"
                          alt="支付宝二维码" class="qr-code" />
                <p class="donation-text">如果这个插件对您有帮助，欢迎请作者喝杯咖啡 ☕</p>
              </div>
            </div>
          </div>
      </el-tab-pane>




    </el-tabs>

    <!-- 配置管理按钮 -->
    <div class="config-section">
      <el-button type="info" @click="openConfigPage">配置管理</el-button>
    </div>



    <!-- Mock编辑弹窗 -->
    <el-dialog
      :title="mockModalTitle"
      :visible.sync="mockModalVisible"
      width="500px"
      @close="closeMockModal">
      <el-form :model="currentMock" label-width="100px">
        <el-form-item label="原始URL:">
          <el-input
            v-model="currentMock.url"
            placeholder="如：api.baidu.com/mes/deve/add">
          </el-input>
        </el-form-item>
        <el-form-item label="请求方法:">
          <el-select v-model="currentMock.method" placeholder="选择方法">
            <el-option label="ALL" value=""></el-option>
            <el-option label="GET" value="GET"></el-option>
            <el-option label="POST" value="POST"></el-option>
            <el-option label="PUT" value="PUT"></el-option>
            <el-option label="DELETE" value="DELETE"></el-option>
          </el-select>
        </el-form-item>
<!--        <el-form-item label="状态码:">
          <el-input-number
            v-model="currentMock.status"
            :min="100"
            :max="599"
            :step="1">
          </el-input-number>
        </el-form-item>-->
<!--        <el-form-item label="延迟(ms):">
          <el-input-number
            v-model="currentMock.delay"
            :min="0"
            :step="100">
          </el-input-number>
        </el-form-item>-->
        <el-form-item label="Mock数据:">
          <el-input
            v-model="currentMock.response"
            type="textarea"
            :rows="6"
            placeholder='{"a": 1, "message": "success"}'>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="currentMock.enabled">启用此Mock规则</el-checkbox>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="closeMockModal">取消</el-button>
        <el-button type="primary" @click="saveMock">保存</el-button>
      </div>
    </el-dialog>

    <!-- 请求详情弹窗 -->
    <el-dialog
      title="请求详情"
      :visible.sync="requestModalVisible"
      width="70%"
      @close="closeRequestModal">
      <div v-if="currentRequest">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="URL">{{ currentRequest.url }}</el-descriptions-item>
          <el-descriptions-item label="方法">{{ currentRequest.method }}</el-descriptions-item>
          <el-descriptions-item label="状态码">{{ currentRequest.status }}</el-descriptions-item>
          <el-descriptions-item label="时间">{{ formatTime(currentRequest.timestamp) }}</el-descriptions-item>
        </el-descriptions>
        <div style="margin-top: 20px;">
          <h4>请求头:</h4>
          <pre>{{ formatJSON(currentRequest.headers) }}</pre>
        </div>
        <div style="margin-top: 20px;" v-if="currentRequest.requestBody">
          <h4>请求体:</h4>
          <pre>{{ formatJSON(currentRequest.requestBody) }}</pre>
        </div>
        <div style="margin-top: 20px;" v-if="currentRequest.responseBody">
          <h4>响应体:</h4>
          <pre>{{ formatJSON(currentRequest.responseBody) }}</pre>
        </div>
      </div>
      <div slot="footer">
        <el-button type="primary" @click="createMockFromRequest">创建Mock规则</el-button>
        <el-button @click="closeRequestModal">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import alipayicon from '../../assets/alipay.jpg'
export default {
  name: 'PopupApp',
  data() {
    return {
      alipayicon,
      isEnabled: true,
      activeTab: 'mocks',
      newDomain: '',
      domainList: [],
      requestFilter: '',
      methodFilter: '',
      requestList: [],
      mockList: [],
      mockModalVisible: false,
      requestModalVisible: false,
      editingMockIndex: -1,
      domainindexEditIndex: null,
      currentMock: {
        url: '',
        method: '',
        status: 200,
        delay: 0,
        response: '',
        enabled: true
      },
      currentRequest: null,
      debuggerStatus: {
        enabled: false,
        attachedTabs: [],
        pendingRequests: 0
      }
    }
  },
  computed: {
    mockModalTitle() {
      return this.editingMockIndex >= 0 ? '编辑Mock规则' : '新增Mock规则'
    },
    filteredRequests() {
      let filtered = this.requestList
      if (this.requestFilter) {
        filtered = filtered.filter(req => 
          req.url.toLowerCase().includes(this.requestFilter.toLowerCase()) ||
          req.method.toLowerCase().includes(this.requestFilter.toLowerCase())
        )
      }
      if (this.methodFilter) {
        filtered = filtered.filter(req => req.method === this.methodFilter)
      }
      return filtered
    }
  },
  mounted() {
    this.loadData()
    this.refreshDebuggerStatus()
  },
  methods: {
    async loadData() {
      try {
        // 加载扩展状态
        const result = await chrome.storage.local.get(['isEnabled'])
        this.isEnabled = result.isEnabled !== false
        
        // 加载域名白名单
        const domainResult = await chrome.storage.local.get(['whitelist'])
        this.domainList = this.computedFun_domainliststr2Obj(domainResult.whitelist || [])
        console.log("this.domainList -->  : ","color:#f0f;", this.domainList);

        // 加载Mock规则
        const mockResult = await chrome.storage.local.get(['mockList'])
        this.mockList = mockResult.mockList || []
        
        // 加载请求历史
        const requestResult = await chrome.storage.local.get(['requestHistory'])
        this.requestList = (requestResult.requestHistory || []).slice(-100) // 只显示最近100条
      } catch (error) {
        console.error('加载数据失败:', error)
        this.$message.error('加载数据失败')
      }
    },
    async triggerUdpateDomain(domain,domainindex) {
      domain._edit=false
      await this.saveDomainList()
      this.domainindexEditIndex=''
    },
    async toggleExtension() {
      try {
        await chrome.storage.local.set({ isEnabled: this.isEnabled })
        this.$message.success(this.isEnabled ? '扩展已启用' : '扩展已禁用')
      } catch (error) {
        console.error('切换扩展状态失败:', error)
        this.$message.error('操作失败')
      }
    },
    computedFun_domainliststr2Obj(domainliststr) {
      return domainliststr?.map(str=>{
        return {
          _edit:false,
          str:str,
        }
      })
    },
    
    async addDomain() {
      if (!this.newDomain.trim()) {
        this.$message.warning('请输入域名')
        return
      }
      
      if (this.domainList?.map(i2=>i2?.str).includes(this.newDomain.trim())) {
        this.$message.warning('域名已存在')
        return
      }
      
      this.domainList.push({
        _edit:false,
        str:this.newDomain.trim()
      })
      this.newDomain = ''
      await this.saveDomainList()
    },
    
    async removeDomain(index) {
      this.domainList.splice(index, 1)
      await this.saveDomainList()
    },
    
    async saveDomainList() {
      try {
        await chrome.storage.local.set({ whitelist: this.domainList?.map(i2=>i2?.str)?.filter(i=>i) })
        this.$message.success('域名白名单已更新')
      } catch (error) {
        console.error('保存域名白名单失败:', error)
        this.$message.error('保存失败')
      }

      //通知 background.js修改数据
      // 通知后台脚本设置变更
      chrome.runtime.sendMessage({
        type: 'SETTINGS_UPDATED',
        settings: this.settings,
        whitelist: this.domainList||[]
      });

    },
    
    async clearRequests() {
      this.requestList = []
      try {
        await chrome.storage.local.set({ requestHistory: [] })
        this.$message.success('请求列表已清空')
      } catch (error) {
        console.error('清空请求列表失败:', error)
        this.$message.error('操作失败')
      }
    },
    
    async refreshRequests() {
      await this.loadData()
      this.$message.success('请求列表已刷新')
    },
    
    showMockModal(mock = null, index = -1) {
      this.editingMockIndex = index
      if (mock) {
        this.currentMock = { ...mock }
      } else {
        this.currentMock = {
          url: '',
          method: '',
          status: 200,
          delay: 0,
          response: '',
          enabled: true
        }
      }
      this.mockModalVisible = true
    },
    
    closeMockModal() {
      this.mockModalVisible = false
      this.editingMockIndex = -1
    },
    
    async saveMock() {
      if (!this.currentMock.url.trim()) {
        this.$message.warning('请输入URL')
        return
      }
      
      try {
        JSON.parse(this.currentMock.response || '{}')
      } catch (error) {
        this.$message.error('Mock数据格式错误，请输入有效的JSON')
        return
      }
      
      if (this.editingMockIndex >= 0) {
        this.mockList.splice(this.editingMockIndex, 1, { ...this.currentMock })
      } else {
        this.mockList.push({ ...this.currentMock })
      }
      
      await this.saveMockList()
      this.closeMockModal()
    },
    
    editMock(index) {
      this.showMockModal(this.mockList[index], index)
    },
    
    async deleteMock(index) {
      this.$confirm('确定要删除这个Mock规则吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        this.mockList.splice(index, 1)
        await this.saveMockList()
      })
    },
    
    async saveMockList() {
      try {
        await chrome.storage.local.set({ mockList: this.mockList })
        this.$message.success('Mock规则已更新')
      } catch (error) {
        console.error('保存Mock规则失败:', error)
        this.$message.error('保存失败')
      }
    },
    
    showRequestDetails(request) {
      this.currentRequest = request
      this.requestModalVisible = true
    },
    
    closeRequestModal() {
      this.requestModalVisible = false
      this.currentRequest = null
    },
    
    createMockFromRequest() {
      if (!this.currentRequest) return
      
      const mock = {
        url: this.currentRequest.url,
        method: this.currentRequest.method,
        status: this.currentRequest.status || 200,
        delay: 0,
        response: this.currentRequest.responseBody || '{}',
        enabled: true
      }
      
      this.closeRequestModal()
      this.showMockModal(mock)
    },
    
    openConfigPage() {
      chrome.runtime.openOptionsPage()
    },

    async toggleDebugger() {
      try {
        // 获取当前活动标签页
        const [tab] = await chrome.tabs.query({active: true, currentWindow: true})
        
        if (!tab) {
          this.$message.error('无法获取当前标签页')
          return
        }

        const action = this.debuggerStatus.enabled ? 'STOP_DEBUGGING' : 'START_DEBUGGING'
        
        // 发送消息给background script
        const response = await chrome.runtime.sendMessage({
          action: action,
          tabId: tab.id
        })
        
        if (response && response.success) {
          this.debuggerStatus.enabled = !this.debuggerStatus.enabled
          if (this.debuggerStatus.enabled) {
            this.debuggerStatus.attachedTabs.push(tab.id)
          } else {
            this.debuggerStatus.attachedTabs = this.debuggerStatus.attachedTabs.filter(id => id !== tab.id)
          }
          
          const statusText = this.debuggerStatus.enabled ? '已启动' : '已停止'
          this.$message.success(`Debugger模式${statusText}`)
        } else {
          this.$message.error('Debugger操作失败，请检查权限设置')
        }
      } catch (error) {
        console.error('切换Debugger模式失败:', error)
        this.$message.error('操作失败: ' + error.message)
      }
    },

    async refreshDebuggerStatus() {
      try {
        const response = await chrome.runtime.sendMessage({
          action: 'GET_DEBUGGER_STATUS'
        })
        
        if (response) {
          this.debuggerStatus.attachedTabs = response.attachedTabs || []
          this.debuggerStatus.pendingRequests = response.pendingRequests || 0
          this.debuggerStatus.enabled = this.debuggerStatus.attachedTabs.length > 0
          // this.$message.success('状态已刷新')
        }
      } catch (error) {
        console.error('获取Debugger状态失败:', error)
        this.$message.error('获取状态失败')
      }
    },
    
    getMethodTagType(method) {
      const types = {
        'GET': 'success',
        'POST': 'primary',
        'PUT': 'warning',
        'DELETE': 'danger'
      }
      return types[method] || 'info'
    },
    
    getStatusTagType(status) {
      if (status >= 200 && status < 300) return 'success'
      if (status >= 300 && status < 400) return 'warning'
      if (status >= 400) return 'danger'
      return 'info'
    },
    
    formatTime(timestamp) {
      return new Date(timestamp).toLocaleString()
    },
    
    formatJSON(obj) {
      try {
        if (typeof obj === 'string') {
          return JSON.stringify(JSON.parse(obj), null, 2)
        }
        return JSON.stringify(obj, null, 2)
      } catch (error) {
        return obj
      }
    }
  }
}
</script>

<style scoped>
.container {
  width: 666px;
  min-height: 500px;
  padding: 16px;
  background: #f5f5f5;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding: 12px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.header h1 {
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
  margin: 0;
}

.status {
  display: flex;
  align-items: center;
  gap: 8px;
}

.section {
  background: white;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 16px;
}

.section h3 {
  font-size: 14px;
  font-weight: 600;
  color: #2c3e50;
  margin: 0 0 12px 0;
}

.input-group {
  display: flex;
  gap: 8px;
  margin-bottom: 16px;
}

.input-group .el-input {
  flex: 1;
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid #e9ecef;
  font-size: 14px;
  font-weight: 500;
  color: #2c3e50;
}

.domain-items {
  list-style: none;
  padding: 0;
  margin: 0;
  max-height: 200px;
  overflow-y: auto;
}

.domain-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  background: #f8f9fa;
  border-radius: 4px;
  margin-bottom: 4px;
}

.domain-name {
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 12px;
  color: #2c3e50;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.controls {
  display: flex;
  gap: 8px;
}

.filter-bar {
  display: flex;
  gap: 8px;
  margin-bottom: 16px;
}

.request-table, .mock-table {
  max-height: 300px;
  overflow-y: auto;
}

.request-item, .mock-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 4px;
  margin-bottom: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.request-item:hover, .mock-item:hover {
  background: #e9ecef;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.request-info, .mock-info {
  flex: 1;
}

.request-url, .mock-url {
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 12px;
  font-weight: 500;
  color: #2c3e50;
  margin-bottom: 4px;
  word-break: break-all;
}

.request-meta, .mock-meta {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 11px;
}

.request-time, .mock-delay {
  color: #6c757d;
  font-size: 11px;
}

.mock-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

.config-section {
  text-align: center;
  margin-top: 16px;
}

.debugger-section {
  background: white;
  border-radius: 8px;
  padding: 16px;
  margin-top: 16px;
  border: 1px solid #e9ecef;
}

.debugger-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.debugger-header h4 {
  font-size: 14px;
  font-weight: 600;
  color: #2c3e50;
  margin: 0;
}

.debugger-status {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 12px;
  flex-wrap: wrap;
}

.debugger-info {
  margin-top: 12px;
}

.debugger-info .el-alert {
  padding: 8px 12px;
}

.debugger-info .el-alert__description {
  font-size: 12px;
  line-height: 1.4;
}

pre {
  background: #f8f9fa;
  padding: 12px;
  border-radius: 4px;
  font-size: 12px;
  line-height: 1.4;
  overflow-x: auto;
  max-height: 200px;
  overflow-y: auto;
}

/* Element UI 样式覆盖 */
.el-tabs--border-card {
  border: none;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.el-tabs--border-card > .el-tabs__content {
  padding: 16px;
}

.el-tab-pane {
  padding: 0;
}

.el-dialog__body {
  padding: 20px;
}

.el-form-item {
  margin-bottom: 16px;
}

.el-descriptions {
  margin-bottom: 16px;
}
</style>